using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 【通用UI缩放动画控制器】
/// 适用场景：点击按钮时，让 UI 元素以缩放动画的方式显示/隐藏
/// 用法：将该脚本挂在一个物体上，设置UI对象和按钮对象，点击按钮即自动触发动画
/// </summary>
public class UIScaleAnimator : MonoBehaviour
{
    [Header("UI元素")]
    public RectTransform uiElement; // 目标UI元素

    [Header("控制按钮")]
    public Button toggleButton; // 控制显示/隐藏的按钮

    [Header("动画参数")]
    public float scaleSpeed = 3f; // 缩放速度（越大越快）

    private Vector3 targetScaleShow = Vector3.one;     // 完整显示的缩放值 (1,1,1)
    private Vector3 targetScaleHide = Vector3.zero;    // 隐藏时缩放值 (0,0,0)

    private bool isShowing;       // 当前是否是显示状态
    private bool isAnimating;     // 是否正在播放动画

    private void Start()
    {
        // 初始化显示状态
        isShowing = uiElement.localScale == targetScaleShow;
        isAnimating = false;

        // 绑定按钮点击事件
        if (toggleButton != null)
            toggleButton.onClick.AddListener(OnToggleClick);
    }

    private void Update()
    {
        if (isAnimating)
        {
            AnimateScale();
        }
    }

    /// <summary>
    /// 按钮点击时切换状态
    /// </summary>
    private void OnToggleClick()
    {
        if (!isAnimating)
        {
            isShowing = !isShowing;
            isAnimating = true;
            toggleButton.interactable = false;
        }
    }

    /// <summary>
    /// 播放缩放动画
    /// </summary>
    private void AnimateScale()
    {
        Vector3 target = isShowing ? targetScaleShow : targetScaleHide;
        uiElement.localScale = Vector3.MoveTowards(uiElement.localScale, target, scaleSpeed * Time.deltaTime);

        // 动画完成后重置状态
        if (uiElement.localScale == target)
        {
            isAnimating = false;
            toggleButton.interactable = true;
        }
    }
}
